/**
 * 
 */
package com.jm.web.form.baseitem;

import java.io.IOException;
import java.sql.ResultSet;

import javax.servlet.jsp.JspWriter;

import net.sf.json.JSONObject;

import com.jm.utils.AttributeBuilder;
import com.jm.utils.StringBuilderEx;
import com.jm.utils.StringHelper;
import com.jm.web.data.BaseDataEntity;
import com.jm.web.data.JMForm;
import com.jm.web.form.support.FieldItem;
import com.jm.web.form.support.FormItem;
import com.jm.web.tags.support.BaseTag;

/**
 * @author yanjie
 * Dec 10, 2011 8:13:01 AM
 */
public class MultiSelectItem extends ListItem{
	private String strType = "text"; 
	protected String otherdata = "";
	protected StringBuffer data = new StringBuffer();
	protected boolean bDataEmpty = true;
	
	@Override
	public void InitTag(BaseTag tag) {
		super.InitTag(tag);
		this.setReadonly(true);//设置默认为true
		this.setNodeName(FieldItem.TAG_ITEMNAME);
	}
	
	@Override
	protected void processDataSourcelist() {
		if(this.getUtils() != null && StringHelper.Length(this.strDataSource) > 0 && StringHelper.Length(this.strSql) > 0){
			try {
				StringBuilderEx temp = null;
				String key = StringHelper.Format("multi-%1$s-%2$s",this.strDataSource,this.strSql);
				if(this.getBaseTag().getPage().listItemDataContainsKey(key)){
					otherdata = (String)this.getBaseTag().getPage().getListItemData(key);
				}else{
					temp = new StringBuilderEx();
					ResultSet rs = this.getUtils().executeQuery(this.strDataSource, this.strSql);
					int colCount = 0;
					if(rs != null)
						colCount = rs.getMetaData().getColumnCount();
					
					while(rs.next())
					{
						JSONObject json = new JSONObject();
						if(colCount == 1){
							String colName1 = StringHelper.getValue(rs.getMetaData().getColumnName(1));
							String colValue1 = StringHelper.getValue(rs.getString(1)) ;
							
							json.put("value",colValue1);
							json.put("text",colName1.startsWith("i18n") ? this.getUtils().i18n(colValue1) : colValue1);
							
						}else if(colCount >= 2){
							String colName2 = StringHelper.getValue(rs.getMetaData().getColumnName(2));
							String colValue2 = StringHelper.getValue(rs.getString(2)) ;
							
							json.put("value",StringHelper.getValue(rs.getString(1)));
							json.put("text",(colName2.startsWith("i18n")) ? this.getUtils().i18n(colValue2) : colValue2);
							
							if(colCount > 2){
								for(int i = 3 ;i<=colCount ;i++){
									String colNamei = StringHelper.getValue(rs.getMetaData().getColumnName(i));
									String colValuei = StringHelper.getValue(rs.getString(i)) ;
									json.put(StringHelper.getValue(rs.getMetaData().getColumnName(i)),
											(colNamei.startsWith("i18n")) ? this.getUtils().i18n(colValuei) : colValuei);
								}
							}
						}
						
						if(!this.bDataEmpty){
							temp.Append(",");
						}else{
							this.bDataEmpty = false;
						}
						
						temp.Append(json.toString());
					}
					rs.close();
					data.append(temp.toString());
					this.getBaseTag().getPage().addListItemData(key,this.getName());
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	protected void processRawcodelist() {
		if(StringHelper.IsNullOrEmpty(this.strCodeList))
			return ;
		
		String [] sets = this.strCodeList.split("[;]");
		for(int i = 0 ;i<sets.length;i++)
		{
			String strTemp = sets[i].trim();
			if(StringHelper.IsNullOrEmpty(strTemp))
				continue;
			
			String [] keyvalue  = strTemp.split("[|]");
			String value = keyvalue[0];
			String text = keyvalue[0];
			
			if(keyvalue.length == 2){
				if(StringHelper.IsNullOrEmpty(keyvalue[0]))
					continue;
				
				if(StringHelper.IsNullOrEmpty(keyvalue[1]))
					continue;
				value = keyvalue[0];
				text = keyvalue[1];
				
				//addListItem(new Item(keyvalue[0], keyvalue[1]));
			}else if(keyvalue.length == 1){
				if(StringHelper.IsNullOrEmpty(keyvalue[0]))
					continue;
				
				//addListItem(new Item(keyvalue[0], keyvalue[0]));
				value = keyvalue[0];
				text = keyvalue[0];
			}
			
			if(!this.bDataEmpty){
				data.append(",");
			}else{
				this.bDataEmpty = false;
			}
			data.append("{");
			data.append("\"text\":\"").append(text).append("\"");
			data.append(",\"value\":\"").append(value).append("\"");
			data.append("}");
		}
	}
	
	
	@Override
	public void renderBegin(JspWriter writer) {
		if(this.getBaseTag() != null && this.getBaseTag().isDSP())
			super.renderBegin(writer);
	}
	
	@Override
	public void renderEnd(JspWriter writer) {
		if(this.getBaseTag() != null && this.getBaseTag().isDSP())
			super.renderEnd(writer);
	}
	
	@Override
	public void onRenderSingleBody(JspWriter writer, FormItem item) {
		StringBuilderEx sb = new StringBuilderEx();
		int textWidth = Integer.parseInt(StringHelper.getValue(this.getWidth(),"100").replace("px",""));
		sb.Append("<div id=\"%2$s_field\" style=\"width:%1$spx;left: 0;position: relative;top: 0;\">",
				textWidth,
				this.getName());
		textWidth = textWidth - 17 ;
		this.setWidth(StringHelper.Format("%1$spx",textWidth));
		
		if("text".equals(this.getType())){
			if(!this.GetExtValue("single",true)){
				sb.Append("\r\n<input type='hidden' xtype=\"multiselect\" ");
				sb.Append(" id='%1$s'",this.getId());
				sb.Append(" textid='%1$s_text'",this.getId());
				sb.Append(" caption='%1$s'",this.getCaption());
				sb.Append(" name='%1$s'",this.getName());
				if(!StringHelper.IsNullOrEmpty(this.getValue()))
				{
					sb.Append(" value='%1$s'",this.getValue());
				}
				if(!StringHelper.IsNullOrEmpty(this.GetExtValue("action","")))
				{
					sb.Append(" action='%1$s'",this.GetExtValue("action",""));
				}
				
				if(!StringHelper.IsNullOrEmpty(this.GetExtValue("actionvalue","")))
				{
					sb.Append(" actionvalue='%1$s'",this.GetExtValue("actionvalue",""));
				}
				sb.Append(" />");
			}
			sb.Append("\r\n<input type='text' xtype=\"multiselect\" autocomplete=\"off\" ");
			AttributeBuilder attributesBuilder = new AttributeBuilder();
			attributesBuilder.InitFromHashtable(this.extAttrList,true);
			
			attributesBuilder.Append("style",";width:"+this.getWidth()+";");
			attributesBuilder.Remove("required");
			attributesBuilder.Remove("rule");
			attributesBuilder.Remove("msg");
			attributesBuilder.Remove("config");
			
			FillAttributeBuilder(attributesBuilder);
			
			if(!StringHelper.IsNullOrEmpty(this.getValue()))
			{
				attributesBuilder.Set(TAG_VALUE.toLowerCase(), this.getValue());
			}
			
			if(!this.GetExtValue("single",true)){
				attributesBuilder.Set("name",StringHelper.Format("%1$s_text",this.getName()));
				attributesBuilder.Set("id",StringHelper.Format("%1$s_text",this.getId()));
				attributesBuilder.Set("hiddenid",StringHelper.Format("%1$s",this.getId()));
				attributesBuilder.Set("value='%1$s'",this.GetExtValue("textvalue",""));
				attributesBuilder.Set("single","false");
			}else{
				attributesBuilder.Set("single","true");
			}
			
			
			sb.Append(attributesBuilder.ToOutputString());
			sb.Append(" />");
		}else if("textarea".equals(this.getType())){
			sb.Append("\r\n<textarea xtype=\"multiselect\" ");
			AttributeBuilder attributesBuilder = new AttributeBuilder();
			attributesBuilder.InitFromHashtable(this.extAttrList,true);
	
			attributesBuilder.Remove("required");
			attributesBuilder.Remove("rule");
			attributesBuilder.Remove("msg");
			FillAttributeBuilder(attributesBuilder);
			sb.Append(attributesBuilder.ToOutputString());
			sb.Append(" >");
			if(!StringHelper.IsNullOrEmpty(this.getValue()))
			{
				sb.Append(this.getValue());
			}
			sb.Append("</textarea>");
		}else if("table".equals(this.getType())){
			sb.Append("<table width=\"%1$s\" class=\"listing\" style=\"float:left;border: 1px solid #7F9DB9 !important;\" id=\"%2$s_table\"><tbody>",this.getWidth(),this.getId());
			JMForm form = this.getBaseTag().getPage().getUtils().getForm();
			String[] valueAy = form.gpsvs(this.getName());
			String[] textAy = form.gpsvs(this.getName()+"_text");
			
			BaseDataEntity tempConfig = this.getConfig("config");
			int columncnt = tempConfig.gpiv("columncnt",1);
			if(valueAy != null && valueAy.length >0){
				StringBuilderEx td = new StringBuilderEx();
				for (int i = 0; i < valueAy.length; i++) {
					td.Append("<td>");
					td.Append("<div class=\"jmx-tab-strip-close\" tableid=\"%1$s_table\" onclick=\"$P.deletemultiselectitem(this)\" style=\"padding-right:2px;margin-top:2px;margin-left:2px;\" >&nbsp;</div>",this.getId());
					td.Append(StringHelper.getValue(textAy[i],"&nbsp;"));
					td.Append("<input type=\"hidden\" id=\"%1$s\" name=\"%1$s\" value=\""+StringHelper.getValue(valueAy[i],"")+"\"/>",this.getName());
					td.Append("<input type=\"hidden\" id=\"%1$s_text\" name=\"%1$s_text\" value=\""+StringHelper.getValue(textAy[i],"")+"\"/>",this.getName());
					td.Append("</td>");
					
					if((i+1)%columncnt ==0 || i== valueAy.length -1){
						if(i== valueAy.length -1 && (i+1)%columncnt >0){
							int subCnt = columncnt - (i+1)%columncnt;//补充td
							for(int k=0;k<subCnt;k++){
								td.Append("<td>&nbsp;</td>");
							}
						}
						
						sb.Append("<tr>%1$s</tr>",td);
						td.Reset();
					}
				}
			}else{
				sb.Append("<tr><td style=\"padding:0px;border:0px;\">&nbsp;</td></tr>");
			}
			sb.Append("</tbody></table>");
		}
		
		BaseDataEntity tempConfig = this.getConfig("config");
		tempConfig.SetParamValue("me","##me");
		tempConfig.SetParamValue("datakey",this.getName());
		tempConfig.SetParamValue("type",this.getType());
		tempConfig.SetParamValue("windowWidth",this.GetExtValue("windowWidth","400"));
		tempConfig.SetParamValue("windowHeight",this.GetExtValue("windowHeight","400"));
		
		StringBuffer strconfig = new StringBuffer();
		strconfig.append(tempConfig.ToJSONString().replaceAll("\"","'").replaceAll("'##me'","\\$(this).prev()[0]"));
		strconfig.insert(strconfig.length() - 1,",'onpicked':'"+this.GetExtValue("onpicked","null").replaceAll("'","\\\\'")+"'");
		
		sb.Append("<img style=\"margin:0;padding:0;height: 20px; width: 17px;cursor: pointer;position: absolute;_bottom:1px;%1$s\"",this.GetExtValue("imgStyle", ""));
		sb.Append(" src=\""+this.getBaseTag().getPage().getContextPath()+"/include/images/default/icon_datapicker_1.gif\"");
		sb.Append(" id=\"%1$s_select\" onclick=\"$P.multiselect(%2$s);return false;\" />"
				,this.getId()
				,strconfig.toString()
					//.replaceAll("'##picked'",this.GetExtValue("onpicked","null"))
				);
		
		sb.Append("</div>");
		try {
			writer.write(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void OnSetProperty(String strName, String strValue) {
		if("type".equalsIgnoreCase(strName))
		{
			this.strType = StringHelper.getValue(strValue,this.strType);
			return;
		}
		super.OnSetProperty(strName, strValue);
	}

	public String getType() {
		return strType;
	}

	public void setType(String strType) {
		this.strType = strType;
	}

	public StringBuffer getData() {
		return data;
	}

	public void setData(StringBuffer data) {
		this.data = data;
	}

	public String getOtherdata() {
		return otherdata;
	}

	public void setOtherdata(String otherdata) {
		this.otherdata = otherdata;
	}
}
